package com.digitalchina.lxnsy.toolkit;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.activity.old.LoginGuideActivity;
import com.digitalchina.lxnsy.activity.old.MainActivity;
import com.digitalchina.lxnsy.constant.Constant;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.sy.login.LoginActivity;
import com.digitalchina.lxnsy.toolkit.statusbar.SystemBarTintManager;
import com.digitalchina.lxnsy.xml.CommonXML;
import com.digitalchina.lxnsy.xml.UserXML;
import com.jude.easyrecyclerview.decoration.DividerDecoration;
import com.jude.easyrecyclerview.decoration.SpaceDecoration;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * ================================================
 * 项目名称：杨凌农业大数据
 * 类描述：其他工具类
 * 包名：com.digitalchina.bigdata.toolkit
 * 创建人：郑皓
 * 创建时间：2016/4/12 17:18
 * 修改备注：
 * ================================================
 */
public class Utils {

    /**
     * 判断用户是否首次打开APP
     *
     * @param poContext
     * @return false 没有登录
     */
    public static boolean isFirstOpen(Context poContext) {

        return CommonXML.getIsFirstOpenStatus(poContext).equals(UserXML.USER_IS_LOGIN_VALUE);
    }

    /**
     * 判断用户是否登录
     *
     * @param poContext
     * @return false 没有登录
     */
    public static boolean isLogin(Context poContext) {

        return UserXML.getLoginStatus(poContext).equals(UserXML.USER_IS_LOGIN_VALUE);
    }

    /**
     * 未登录则跳转到登录界面
     *
     * @param poContext
     * @return
     */
    public static void notLoginGoto(Context poContext) {

        if (!isLogin(poContext))
            //GotoUtil.gotoActivity((Activity) poContext, LoginGuideActivity.class);
            GotoUtil.gotoActivity((Activity) poContext, LoginActivity.class);

    }

    /**
     * 判断当前网络状态
     *
     * @param poContext
     * @return
     */
    public static boolean isInternetAvailable(Context poContext) {
        if (poContext == null)
            return false;
        ConnectivityManager loConnMgr = (ConnectivityManager) poContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo loNetInfo = loConnMgr.getActiveNetworkInfo();
        if (loNetInfo != null)
            return loNetInfo.isAvailable();
        return false;
    }

    public static boolean isConnected(Context context) {
        ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conn.getActiveNetworkInfo();
        return (info != null && info.isConnected());
    }


    /**
     * 启动验证码按钮线程
     *
     * @param poContext
     * @param poHandler
     * @param piSecs
     * @param psPrefix
     */
    public static void startForbitSendVerifyCode(final Context poContext, final Handler poHandler,
                                                 final int piSecs, final String psPrefix) {
        new Thread() {
            @Override
            public void run() {
                for (int i = piSecs - 1; i >= 0; i--) {

                    Message loMsg = new Message();
                    if (i != 0) {
                        loMsg.what = MSG.MSG_SEND_VERIFY_CODE_TIP;
                        String lsText = psPrefix == null ? "" : psPrefix;
                        if (i < 10)
                            lsText += " " + i + "秒";
                        else
                            lsText += "" + i + "秒";
                        loMsg.obj = lsText;
                    } else {
                        loMsg.what = MSG.MSG_SEND_VERIFY_CODE_END;
                    }
                    poHandler.sendMessage(loMsg);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    }
                }
            }
        }.start();
    }

    /**
     * 手机号码校验
     *
     * @param mobiles 手机号码
     * @return
     */
    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern
                .compile("^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$");
//                .compile("^((13[0-9])|(15[^4,//D])|(18[0,5-9]))//d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }


    /**
     * 资讯完整图片路径
     *
     * @param imgurl
     * @return
     */
    public static String infoImageUrl(String imgurl) {
        if (StringUtil.isStrEmpty(imgurl))
            return new StringBuilder().append(URL.SERVER).append("static/img/default.png").toString();
        else
            return StringUtil.jointString(URL.URL_SHOW_IMAGE + imgurl + Constant.SHOW_IMAGE_TYPE_SMALL);
    }

    /**
     * 完整图片路径
     *
     * @param imgurl
     * @return
     */
    public static String imageUrl(String imgurl) {
        if (StringUtil.isStrEmpty(imgurl))
            return new StringBuilder().append(URL.SERVER).append("static/img/default.png").toString();
        else
            return new StringBuilder().append(URL.URL_SHOW_IMAGE).append(imgurl).append(Constant.SHOW_IMAGE_TYPE_MID).toString();
    }

    /**
     * 完整网络地址
     *
     * @param url
     * @return
     */
    public static String url(String url) {
        if (url.startsWith("/"))
            url = url.substring(1);

        return new StringBuffer().append(URL.SERVER).append(url).toString();
    }


    /**
     * 隐藏软键盘
     *
     * @param activity
     */
    public static void hideWindow(Activity activity) {
        View view = activity.getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputmanger = (InputMethodManager) activity
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 隐藏软键盘
     *
     * @param activity
     * @return isOpen
     */
    public static void hideKeyBoard(Activity activity) {
        View view = activity.getWindow().peekDecorView();
        boolean isOpen = false;
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) activity
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            isOpen = imm.isActive();

            if (!isOpen) {
                return;
            } else {
                hideWindow(activity);
            }
        }
    }

    /**
     * 判断SD卡是否存在
     */
    public static boolean hasSdcard() {
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }


    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    /**
     * 格式化价格为小数点后两位
     *
     * @param price 待格式化价格
     * @return
     */
    public static String formatPrice(String price) {

        return new BigDecimal(price).setScale(2, BigDecimal.ROUND_HALF_UP).toString();

    }


    /**
     * 格式化价格为小数点后两位
     *
     * @param price 待格式化价格
     * @return
     */
    public static String formatPrice(BigDecimal price) {

        return price.setScale(2, BigDecimal.ROUND_HALF_UP).toString();

    }


    /**
     * 设置状态栏透明
     *
     * @param activity
     */
    public static void setTitleBarTranslucent(Activity activity) {
        // 状态栏透明, 4.4+生效
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            SystemBarTintManager systemBarTintManager = new SystemBarTintManager(activity);
            systemBarTintManager.setStatusBarTintEnabled(true);
            systemBarTintManager.setStatusBarTintResource(android.R.color.transparent);
        }
    }


    /**
     * Glide加载网络图片
     */
    public static void displayImage(Context context, String imgUrl, ImageView imageView) {

        Glide.with(context)
                .load(Utils.imageUrl(imgUrl))
                .into(imageView);
    }

    /**
     * Glide加载CMS图片
     */
    public static void displayCMSImage(Context context, String imgUrl, ImageView imageView) {

        if (imgUrl.startsWith("/"))
            imgUrl = imgUrl.substring(1);

        Glide.with(context)
                .load(URL.SERVER + imgUrl)
                .into(imageView);
    }


    /**
     * 设置recyclerView fixed space divider
     *
     * @param context
     * @return
     */
    public static SpaceDecoration setSpaceDecoration(Context context) {
        SpaceDecoration itemDecoration = new SpaceDecoration(Utils.dip2px(context, 10));//参数是距离宽度
        itemDecoration.setPaddingEdgeSide(true);//是否为左右2边添加padding.默认true.
        itemDecoration.setPaddingStart(true);//是否在给第一行的item添加上padding(不包含header).默认true.
        itemDecoration.setPaddingHeaderFooter(false);//是否对Header于Footer有效,默认false.
        return itemDecoration;
    }

    /**
     * 设置recyclerView space divider
     *
     * @param context
     * @param padSide         是否为左右2边添加padding.默认true.
     * @param padStart        item添加上padding(不包含header).默认true
     * @param padHeaderFooter 是否对Header于Footer有效,默认false
     * @return
     */
    public static SpaceDecoration setSpaceDecoration(Context context, boolean padSide, boolean padStart, boolean padHeaderFooter) {
        SpaceDecoration itemDecoration = new SpaceDecoration(dip2px(context, 10));//参数是距离宽度
        itemDecoration.setPaddingEdgeSide(padSide);//是否为左右2边添加padding.默认true.
        itemDecoration.setPaddingStart(padStart);//是否在给第一行的item添加上padding(不包含header).默认true.
        itemDecoration.setPaddingHeaderFooter(padHeaderFooter);//是否对Header于Footer有效,默认false.
        return itemDecoration;
    }

    /**
     * 设置recyclerView divider
     *
     * @param context
     * @return
     */
    public static DividerDecoration setDividerDecoration(Context context, float height, float paddingLeft, float paddingRight) {

        DividerDecoration dividerDecoration = new DividerDecoration(
                context.getResources().getColor(R.color.colorFontLightGrayE),
                dip2px(context, height),
                dip2px(context, paddingLeft),
                dip2px(context, paddingRight));
        dividerDecoration.setDrawLastItem(false);

        return dividerDecoration;
    }

    // 校验Tag Alias 只能是数字,英文字母和中文
    public static boolean isValidTagAndAlias(String s) {
        Pattern p = Pattern.compile("^[\u4E00-\u9FA50-9a-zA-Z_!@#$&*+=.|]+$");
        Matcher m = p.matcher(s);
        return m.matches();
    }


    /**
     * 从通知栏进入返回到主页
     */
    public static void finishActivity(Activity act) {
        if (ActivityTaskManager.getInstance().size() > 1) {
            act.finish();
        } else {
            GotoUtil.gotoActivity(act, MainActivity.class);
            act.finish();
        }

    }

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        return netInfo != null && netInfo.isConnectedOrConnecting();
    }

    /**
     * 获取当前class name
     *
     * @param context
     * @return
     */
    public static String getCurrentActivityName(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Activity.ACTIVITY_SERVICE);

        // get the info from the currently running task
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);

        ComponentName componentInfo = taskInfo.get(0).topActivity;
        return componentInfo.getClassName();
    }

    /**
     * 调用拨号界面
     *
     * @param phone 电话号码
     */
    public static void callPhone(Context context, String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 字符串反转
     * @param str
     * @return
     */
    public static String reverseByArray(String str)   {
        StringBuffer buf = new StringBuffer(str);
        buf = buf.reverse();
        return buf.toString();
    }

    /**
     * @param urlparam 带分隔的url参数
     * @return
     */
    public static Map<String,String> getUrlParams(String urlparam){
        Map<String,String> map = new HashMap<String,String>();
        String[] param =  urlparam.split("&");
        for(String keyvalue:param){
            String[] pair = keyvalue.split("=");
            if(pair.length==2){
                map.put(pair[0], pair[1]);
            }
        }
        return map;
    }
}